Fix #20429 — Attention layer hardcodes 3-D shape assumptions, breaking N-D inputs#22361
Fix #20429 — Attention layer hardcodes 3-D shape assumptions, breaking N-D inputs#22361pctablet505 wants to merge 2 commits intokeras-team:masterfrom
Attention layer hardcodes 3-D shape assumptions, breaking N-D inputs#22361Conversation
The Attention layer hardcoded axes=[0, 2, 1] in the transpose for dot score calculation, which only works for 3D tensors. When 4D inputs (e.g. from Conv2D/MaxPooling2D) are passed, it raises a dimension mismatch error. Replace ops.transpose(key, axes=[0, 2, 1]) with ops.swapaxes(key, -2, -1) which generalizes to any number of dimensions. Also fix compute_output_shape and compute_output_spec to use relative indices instead of hardcoded positional indices. Fixes keras-team#20429
Summary of ChangesHello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request addresses a limitation in the Keras Highlights
🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console. Changelog
Activity
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
There was a problem hiding this comment.
Code Review
This pull request correctly addresses an issue where the Attention layer was limited to 3-D inputs. The changes to use ops.swapaxes and more general shape computations in compute_output_shape and compute_output_spec are well-implemented and effectively enable support for N-D inputs. The addition of test_attention_nd_inputs provides good test coverage for this new capability.
As a suggestion for further improvement, the docstrings for the Attention layer and its methods still describe input and output shapes in terms of 3-D tensors (e.g., (batch_size, Tq, dim)). To align with the changes and improve user understanding, it would be beneficial to update these to reflect the new N-D support (e.g., (*batch_dims, Tq, dim)). This would be in line with the Keras API design guidelines on documentation.
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## master #22361 +/- ##
=======================================
Coverage 82.95% 82.95%
=======================================
Files 595 595
Lines 66040 66040
Branches 10305 10305
=======================================
Hits 54785 54785
Misses 8639 8639
Partials 2616 2616
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
|
Is this ready for review? It's marked as draft right now. |
Fixes: #20429
This pull request improves the flexibility and correctness of the
Attentionlayer in Keras by updating how attention scores are computed and returned, particularly for inputs with more than 3 dimensions (N-D inputs). The changes ensure that the layer can seamlessly handle high-dimensional data, such as outputs from convolutional layers, and that attention score shapes are computed correctly. Additionally, new tests are added to verify this expanded support.Enhancements to N-Dimensional Input Support:
Updated the computation of attention scores in
_calculate_scoresto useops.swapaxes(key, -2, -1)instead of a fixed axes transpose, allowing for correct handling of N-D inputs.Modified the calculation of the attention scores' output shape in both
compute_output_shapeandcompute_output_specto generalize over N-D inputs, using*query_shape[:-1]andkey_shape[-2]for shape construction. [1] [2]Testing Improvements:
test_attention_nd_inputs) to verify that theAttentionlayer correctly supports 4D inputs (such as those fromConv2Dlayers), including checks for both output and attention score shapes.Problem
The
Attentionlayer assumed inputs are exactly 3-D(batch, time, features). Two concrete failures:ops.transpose(key, axes=[0, 2, 1])— a hard-coded 3-D permutation. For any other rank this raises a shape error or silently produces wrong results.compute_output_shapeandcompute_output_specbuilt output shapes as(query_shape[0], query_shape[1], key_shape[1])— again 3-D only. Callingmodel.predict()(which goes throughcompute_output_spec) on a model with Attention and 4-D inputs failed with a shape error.Fix
ops.transpose(key, axes=[0, 2, 1])withops.swapaxes(key, -2, -1)— works for any rank.(*query_shape[:-1], key_shape[-2])for attention-score shape and(*query_shape[:-1], value_shape[-1])for output shape.Files Changed
keras/src/layers/attention/attention.py—_calculate_scores,compute_output_shape,compute_output_speckeras/src/layers/attention/attention_test.py— new test with 4-D inputs (batch, H, W, C), verifies output and score shapes